package com.bd.volkswagen.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bd.scm.domain.dto.aggrid.AgGridRequest;
import com.bd.scm.domain.dto.device.BdKqFeedbackDto;
import com.bd.scm.domain.dto.device.DeviceDto;
import com.bd.scm.domain.dto.device.DzStDeviceDto;
import com.bd.scm.domain.dto.device.GetDeviceDto;
import com.bd.scm.domain.dto.door.DoorDto;
import com.bd.scm.domain.models.device.BdKqFeedback;
import com.bd.scm.domain.models.device.DzStDevice;
import com.bd.scm.domain.models.device.JuserKqRecord;
import com.bd.scm.domain.models.device.ShowStDevice;
import com.bd.scm.module.device.service.StDeviceService;
import com.bd.scm.module.utils.ResultUtil;
import com.bd.utils.DateUtils;
import com.bd.utils.StringUtils;
import com.bd.utils.vo.Result;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Mason
 * @since 2019-09-03
 */
@RestController
@RequestMapping("/api/stDevice")
public class DeviceController {

    @Autowired
    private StDeviceService stDeviceService;

    /**
     * 获取设备列表
     *
     * @param doorDto
     * @return
     */
    @PostMapping("getStDeviceList")
    public Result getStDeviceList(@RequestBody DoorDto doorDto) {
        return ResultUtil.ok(stDeviceService.getStDeviceList(doorDto));
    }

    /**
     * 设备管理界面--获取设备列表.
     *
     * @param getDeviceDto
     * @return
     */
    @PostMapping("getDevicePages")
    public Result getDevicePages(@RequestBody GetDeviceDto getDeviceDto) {
        IPage<ShowStDevice> page = stDeviceService.getDevicePages(getDeviceDto);
        return ResultUtil.ok(stDeviceService.getDevicePages(getDeviceDto));
    }

    /**
     * 获取设备最大编号+1.
     *
     * @return 现有最大编号+1
     */
    @PostMapping("getMaxIdFromDevices")
    public Result getMaxIdFromDevices() {
        String maxId = stDeviceService.getMaxIdFromDevices();
        return ResultUtil.ok(maxId);
    }

    /**
     * 设备管理界面--获取设备列表.
     *
     * @param deviceDto 新增的设备信息
     * @return 结果
     */
    @PostMapping("saveDevice")
    public Result saveDevice(@RequestBody DeviceDto deviceDto) {
        Result result = Result.ok("新增成功");
        try {
            stDeviceService.saveDevice(deviceDto);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("程序内部错误");
        }
        return result;
    }

    /**
     * 修改设备——获取设备信息.
     *
     * @param deviceDto 设备信息
     * @return 结果
     */
    @PostMapping("getDeviceByBh")
    public Result getDeviceByBh(@RequestBody DeviceDto deviceDto) {
        Result result = null;
        try {
            DeviceDto deviceInfo = stDeviceService.getDeviceByBh(deviceDto);
            result = Result.ok(deviceInfo);
            if (null == deviceInfo) {
                result = Result.error("获取设备信息失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("程序内部错误");
        }
        return result;
    }

    /**
     * 修改设备.
     *
     * @param deviceDto 修改的设备信息
     * @return 结果
     */
    @PostMapping("editDevice")
    public Result editDevice(@RequestBody DeviceDto deviceDto) {
        Result result = Result.ok("修改成功");
        try {
            stDeviceService.editDevice(deviceDto);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("程序内部错误");
        }
        return result;
    }

    /**
     * 删除设备.
     *
     * @param deviceDto 要删除设备的设备信息
     * @return 结果
     */
    @PostMapping("deleteDevice")
    public Result deleteDevice(@RequestBody DeviceDto deviceDto) {
        Result result = Result.ok("修改成功");
        try {
            stDeviceService.deleteDevice(deviceDto);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("程序内部错误");
        }
        return result;
    }


    // 大众考勤 设备开始

    // 查询
    @PostMapping("getDzStDeviceList")
    public Result getDzStDeviceList(@RequestBody DzStDeviceDto dzStDeviceDto) {
        Result result = null;
        try {
            Page<DzStDevice> page = new Page<>(dzStDeviceDto.getPageNumber(), dzStDeviceDto.getPageSize());
            IPage<DzStDevice> pageList = this.stDeviceService.getDzStDeviceList(page, dzStDeviceDto);
            result = ResultUtil.ok(pageList);
        }catch (Exception e){
            e.printStackTrace();
            result = ResultUtil.error("获取数据失败");
        }
        return  result;
    }

    // 手机 查询 2021/09/10 YH
    @PostMapping("getDzStDeviceList2")
    public Result getDzStDeviceList2(@RequestBody DzStDeviceDto dzStDeviceDto) {
        Result result = null;
        try {
            Page<DzStDevice> page = new Page<>(dzStDeviceDto.getPageNumber(), dzStDeviceDto.getPageSize());
            IPage<DzStDevice> pageList = this.stDeviceService.getDzStDeviceList2(page, dzStDeviceDto);
            result = ResultUtil.ok(pageList);
        }catch (Exception e){
            e.printStackTrace();
            result = ResultUtil.error("获取数据失败");
        }
        return  result;
    }

    // 添加
    @PostMapping("insertDzStDevice")
    public Result insertDzStDevice(@RequestBody DzStDeviceDto dzStDeviceDto) {
        Result result = null;
        try {
           // 设备名称
           if(StringUtils.isEmpty(dzStDeviceDto.getMc())){
               return Result.error("设备名称为空");
           }
            String dzStDevice = stDeviceService.insertDzStDevice(dzStDeviceDto);
            if (null == dzStDevice) {
                result = Result.ok("添加设备成功");
            }else{
                result = Result.error("添加设备失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("程序内部错误");
        }
        return result;
    }

    // 修改
    @PostMapping("updateDzStDevice")
    public Result updateDzStDevice(@RequestBody DzStDeviceDto dzStDeviceDto) {
        Result result = null;
        try {
            // 设备名称
            if(StringUtils.isEmpty(dzStDeviceDto.getMc())){
                return Result.error("设备名称为空");
            }
            String dzStDevice = stDeviceService.updateDzStDevice(dzStDeviceDto);
            if (null == dzStDevice) {
                result = Result.ok("修改设备成功");
            }else{
                result = Result.error("修改设备失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("程序内部错误");
        }
        return result;
    }

    // 删除
    @PostMapping("deleteDzStDevice")
    public Result deleteDzStDevice(@RequestBody DzStDeviceDto dzStDeviceDto) {
        Result result = null;
        try {
            // 设备唯一值
            if(StringUtils.isEmpty(dzStDeviceDto.getBh())){
                return Result.error("设备ID为空");
            }
            String dzStDevice = stDeviceService.deleteDzStDevice(dzStDeviceDto);
            if (null == dzStDevice) {
                result = Result.ok("删除设备成功");
            }else{
                result = Result.error("删除设备失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("程序内部错误");
        }
        return result;
    }

    /**
     * 手机打卡数据保存
     * @param juserKqRecord 设备唯一的ID  mJdevid
     * @return
     */
    @PostMapping("saveJuserKqRecord")
    public Result saveJuserKqRecord(@RequestBody JuserKqRecord juserKqRecord, HttpServletRequest request) {
        Result result = null;
        //获取登录人ID
        JSONObject user = null;
        try {
            //添加操作人ID
            if (ObjectUtil.isEmpty(juserKqRecord.getJlogUserId())) {
                return Result.error("用户信息不能为空");
            }
//            user = (JSONObject) request.getSession().getAttribute("user");
//            juserKqRecord.setJlogUserId(user.getString("USERSERIAL"));
//            juserKqRecord.setJlogUserId("75276");
            String currentDateTime = DateUtils.getCurrentDateTime();
            juserKqRecord.setJdatatime(currentDateTime);
//            if(StringUtils.isEmpty(juserKqRecord.getJlogUserId())){
//                result = Result.error("未取得登陆信息");
//                return result;
//            }
            try {
                if (!StringUtils.isEmpty(juserKqRecord.getJlogUserId()) &&
                        !StringUtils.isEmpty(String.valueOf(juserKqRecord.getMjDevid()))
                        && !StringUtils.isEmpty(juserKqRecord.getJdatatime())
                        && !StringUtils.isEmpty(String.valueOf(juserKqRecord.getJlogDir()))) {
                    String kqRecord = stDeviceService.saveJuserKqRecord(juserKqRecord);
                    if (null == kqRecord) {
                        result = Result.ok("保存成功");
                    } else {
                        result = Result.error(kqRecord);
                    }
                } else {
                    result = Result.error("参数无效");
                }
            } catch (Exception e) {
                e.printStackTrace();
                result = ResultUtil.error("保存异常");
            }
        } catch (NullPointerException n) {
            n.printStackTrace();
            result = Result.error("登录信息失效，请重新登录");
        }
        return result;
    }

    /**
     * 手机端定位当天上下班是否已打卡接口开发，返回前端上班是否已打卡，下班是否已打卡
     * @param request
     * @return
     */
    @PostMapping("getUserTtTaskCard")
    public Result getUserTtTaskCard(@RequestBody JuserKqRecord juserKqRecord, HttpServletRequest request) {
        DzStDeviceDto dzStDeviceDto = new DzStDeviceDto();
        Result result = null;
        //获取登录人ID
        JSONObject user = null;
        try {
            if (ObjectUtil.isEmpty(juserKqRecord.getJlogUserId())) {
                return Result.error("用户信息不能为空");
            }
            //添加操作人ID
//            user = (JSONObject) request.getSession().getAttribute("user");
//            dzStDeviceDto.setPkSysUser(user.getString("USERSERIAL"));
//            if(StringUtils.isEmpty(dzStDeviceDto.getPkSysUser())){
//                result = Result.error("未取得登陆信息");
//                return result;
//            }
            dzStDeviceDto.setPkSysUser(juserKqRecord.getJlogUserId());
            List<JSONObject> userTtTaskCard = this.stDeviceService.getUserTtTaskCard(dzStDeviceDto);
            result = Result.ok(userTtTaskCard);
        } catch (NullPointerException n) {
            n.printStackTrace();
            result = Result.error("登录信息失效，请重新登录");
        }
        return result;
    }

    @PostMapping("userConfirm")
    public Result userConfirm(@RequestBody JuserKqRecord userInfo) {
        stDeviceService.userConfirm(userInfo.getJlogUserId());
        return Result.ok("确认成功");
    }

    // 添加 反馈信息 @RequestParam("file") MultipartFile file
    @PostMapping("insertBdKqFeedback")
    public Result insertBdKqFeedback(HttpServletRequest request) {
        Result result = null;
        try {
            BdKqFeedback bdKqFeedback = new BdKqFeedback();
            // id
            bdKqFeedback.setId(getUUID());
            // phoneBrands
            bdKqFeedback.setPhoneBrands(request.getParameter("phoneBrands"));
            // phonesSystem
            bdKqFeedback.setPhonesSystem(request.getParameter("phonesSystem"));
            // phoneOperators
            bdKqFeedback.setPhoneOperators(request.getParameter("phoneOperators"));
            // nowLocation
            bdKqFeedback.setNowLocation(request.getParameter("nowLocation"));
            // remarks
            bdKqFeedback.setRemarks(request.getParameter("remarks"));
            // longitude
            bdKqFeedback.setLongitude(request.getParameter("longitude"));
            // latitude
            bdKqFeedback.setLatitude(request.getParameter("latitude"));
            // userId
            bdKqFeedback.setUserId(request.getParameter("userId"));
            byte[] pictureData2 = new byte[0];
            bdKqFeedback.setPhoto1(pictureData2);
            bdKqFeedback.setPhoto2(pictureData2);
            bdKqFeedback.setPhoto3(pictureData2);
            bdKqFeedback.setPhoto4(pictureData2);
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
            if (files != null && files.size() > 0) {
                for (int i = 0; i < files.size(); i++) {
                    MultipartFile file = files.get(i);
                    //保存图片
                    byte[] pictureData = null;
                    InputStream inputStream = file.getInputStream();
                    pictureData = new byte[(int) file.getSize()];
                    inputStream.read(pictureData);

                    if(1 == (1+i)){
                        bdKqFeedback.setPhoto1(pictureData);
                    }
                    if(2 == (1+i)){
                        bdKqFeedback.setPhoto2(pictureData);
                    }
                    if(3 == (1+i)){
                        bdKqFeedback.setPhoto3(pictureData);
                    }
                    if(4 == (1+i)){
                        bdKqFeedback.setPhoto4(pictureData);
                    }

                }
            }
            System.out.println(bdKqFeedback.toString());
            stDeviceService.insertBdKqFeedback(bdKqFeedback);
            result = Result.ok("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("程序内部错误");
        }
        return result;
    }

    public static String getUUID() {
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        return uuid;
    }

    // 查询反馈信息
    @PostMapping("getBdKqFeedbackList")
    public Result getBdKqFeedbackList(@RequestBody BdKqFeedbackDto bdKqFeedbackDto) {
        Result result = null;
        try {
            Page<BdKqFeedback> page = new Page<>(bdKqFeedbackDto.getPageNumber(), bdKqFeedbackDto.getPageSize());
            IPage<BdKqFeedback> pageList = this.stDeviceService.getBdKqFeedbackList(page, bdKqFeedbackDto);
            result = ResultUtil.ok(pageList);
        }catch (Exception e){
            e.printStackTrace();
            result = ResultUtil.error("获取数据失败");
        }
        return  result;
    }

    /**
     * 反馈信息导出
     *
     * @param serchTxt
     * @param response
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    @RequestMapping(value = "bdKqFeedbackExport")
    public Result bdKqFeedbackExport(String serchTxt, String startDate,String endDate, HttpServletResponse response) throws IOException {
//        BdKqFeedbackDto bdKqFeedbackDto = new BdKqFeedbackDto();
//        bdKqFeedbackDto.setSerchTxt(serchTxt);
//        bdKqFeedbackDto.setStartDate(startDate);
//        bdKqFeedbackDto.setEndDate(endDate);
//        AgGridRequest request = new AgGridRequest();
//        request.setStartRow(0);
//        request.setEndRow(Integer.MAX_VALUE);
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("serchTxt", serchTxt);
//        map.put("startDate", startDate);
//        map.put("endDate", endDate);
//        request.setData(map);
//        Page<BdKqFeedback> page = getPage(request);
//        List<BdKqFeedback> bdKqFeedback = this.stDeviceService.getBdKqFeedbackList(page, bdKqFeedbackDto).getRecords();
//        ExcelUtil.ExportExcel("导出反馈信息列表", response, bdKqFeedback, BdKqFeedback.class);
        return ResultUtil.ok();
    }

//    public <T> Page<T> getPage(AgGridRequest request) {
//        int pageNo = 1;
//        int pageSize = request.getEndRow() - request.getStartRow();
//        if (request.getStartRow() > 0) {
//            pageNo = request.getStartRow() / pageSize + 1;
//        }
//
//        Page<T> page = new Page((long)pageNo, (long)pageSize);
//        return page;
//    }

//    @RequestMapping(value = "/exportExcel")
//    public void exportExcel(String serchTxt, String startDate,String endDate, HttpServletResponse response) throws IOException {
//        // 获取数据
//        BdKqFeedbackDto bdKqFeedbackDto = new BdKqFeedbackDto();
//        bdKqFeedbackDto.setSerchTxt(serchTxt);
//        bdKqFeedbackDto.setStartDate(startDate);
//        bdKqFeedbackDto.setEndDate(endDate);
//        AgGridRequest request = new AgGridRequest();
//        request.setStartRow(0);
//        request.setEndRow(Integer.MAX_VALUE);
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("serchTxt", serchTxt);
//        map.put("startDate", startDate);
//        map.put("endDate", endDate);
//        request.setData(map);
//        Page<BdKqFeedback> page = getPage(request);
//        List<BdKqFeedback> bdKqFeedback = this.stDeviceService.getBdKqFeedbackList(page, bdKqFeedbackDto).getRecords();
//
//        // 获取exec文件 设置值
//        String fileName = "导出反馈信息列表.xlsx";
//        response.setContentType("application/excel");
//        response.setHeader("Content-disposition",
//                "attachment;filename=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
//        String filePath = getClass().getResource("/downLoadTemplate/" + fileName).getPath();
//        filePath = URLDecoder.decode(filePath, "UTF-8");
//        InputStream inputStream = new FileInputStream(filePath);
//        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
//        XSSFSheet sheet = workbook.getSheet("sheet");
//        // 利用XSSFDrawing将图片写入EXCEL
//        XSSFDrawing patriarch  = sheet.createDrawingPatriarch();
//        int rowNum = 1;
//
//        if(bdKqFeedback.size()>0){
//            for (BdKqFeedback kqFeedback : bdKqFeedback) {
//
//                // 先把读进来的图片放到一个ByteArrayOutputStream中，以便产生ByteArray
//                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
//                BufferedImage bufferImg = null;//图片
//
//                XSSFRow row = sheet.createRow(rowNum);
//                // 工号 userNo
//                row.createCell(0).setCellValue(kqFeedback.getUserNo());
//                // 姓名 userName
//                row.createCell(1).setCellValue(kqFeedback.getUserName());
//                // 手机品牌 phoneBrands
//                row.createCell(2).setCellValue(kqFeedback.getPhoneBrands());
//                // 操作系统类型 phonesSystem
//                row.createCell(3).setCellValue(kqFeedback.getPhonesSystem());
//                // 通讯服务商 phoneOperators
//                row.createCell(4).setCellValue(kqFeedback.getPhoneOperators());
//                // 显示位置 nowLocation
//                row.createCell(5).setCellValue(kqFeedback.getNowLocation());
//                // 备注 remarks
//                row.createCell(6).setCellValue(kqFeedback.getRemarks());
//                // 经度 longitude
//                row.createCell(7).setCellValue(kqFeedback.getLongitude());
//                // 纬度 latitude
//                row.createCell(8).setCellValue(kqFeedback.getLatitude());
//
//                // 图片处理
//                // 图片1 photo1
//                //将图片读到BufferedImage
//                InputStream in = new ByteArrayInputStream(kqFeedback.getPhoto1());
//                bufferImg = ImageIO.read(in);
//                // 将图片写入流中
//                ImageIO.write(bufferImg, "png", byteArrayOut);
//                /**
//                 * 该构造函数有8个参数
//                 * 前四个参数是控制图片在单元格的位置，分别是图片距离单元格left，top，right，bottom的像素距离
//                 * 后四个参数，前连个表示图片左上角所在的cellNum和 rowNum，后天个参数对应的表示图片右下角所在的cellNum和 rowNum，
//                 * excel中的cellNum和rowNum的index都是从0开始的
//                 *
//                 */
//                //图片一导出到单元格B2中
//                XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0,
//                        (short) 9, rowNum, (short) 10, rowNum+1);
//                // 插入图片
//                patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut
//                        .toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
//
////                // 图片2 photo2
////                in = new ByteArrayInputStream(kqFeedback.getPhoto2());
////                bufferImg = ImageIO.read(in);
////                // 将图片写入流中
////                ImageIO.write(bufferImg, "png", byteArrayOut);
////                /**
////                 * 该构造函数有8个参数
////                 * 前四个参数是控制图片在单元格的位置，分别是图片距离单元格left，top，right，bottom的像素距离
////                 * 后四个参数，前连个表示图片左上角所在的cellNum和 rowNum，后天个参数对应的表示图片右下角所在的cellNum和 rowNum，
////                 * excel中的cellNum和rowNum的index都是从0开始的
////                 *
////                 */
////                //图片一导出到单元格B2中
////                anchor = new XSSFClientAnchor(0, 0, 0, 0,
////                        (short) 10, rowNum, (short) 11, rowNum+1);
////                // 插入图片
////                patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut
////                        .toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
////
////                // 图片3 photo3
////                in = new ByteArrayInputStream(kqFeedback.getPhoto3());
////                bufferImg = ImageIO.read(in);
////                // 将图片写入流中
////                ImageIO.write(bufferImg, "png", byteArrayOut);
////                /**
////                 * 该构造函数有8个参数
////                 * 前四个参数是控制图片在单元格的位置，分别是图片距离单元格left，top，right，bottom的像素距离
////                 * 后四个参数，前连个表示图片左上角所在的cellNum和 rowNum，后天个参数对应的表示图片右下角所在的cellNum和 rowNum，
////                 * excel中的cellNum和rowNum的index都是从0开始的
////                 *
////                 */
////                //图片一导出到单元格B2中
////                anchor = new XSSFClientAnchor(0, 0, 0, 0,
////                        (short) 11, rowNum, (short) 12, rowNum+1);
////                // 插入图片
////                patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut
////                        .toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
////
////                // 图片4 photo4
////                in = new ByteArrayInputStream(kqFeedback.getPhoto3());
////                bufferImg = ImageIO.read(in);
////                // 将图片写入流中
////                ImageIO.write(bufferImg, "png", byteArrayOut);
////                /**
////                 * 该构造函数有8个参数
////                 * 前四个参数是控制图片在单元格的位置，分别是图片距离单元格left，top，right，bottom的像素距离
////                 * 后四个参数，前连个表示图片左上角所在的cellNum和 rowNum，后天个参数对应的表示图片右下角所在的cellNum和 rowNum，
////                 * excel中的cellNum和rowNum的index都是从0开始的
////                 *
////                 */
////                //图片一导出到单元格B2中
////                anchor = new XSSFClientAnchor(0, 0, 0, 0,
////                        (short) 12, rowNum, (short) 13, rowNum+1);
////                // 插入图片
////                patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut
////                        .toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
//
//                rowNum++;
//            }
//        }
//
//        try {
//            workbook.write(response.getOutputStream());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }


}

